#-*- coding:utf8 -*-
'''
Created on 2012-7-13

@author: Bise
'''
import config
import time
from base import BaseHandler
import tornado.ioloop
from tornado.web import asynchronous
import json

class CometHandler(BaseHandler):
    
    def initialize(self, method = ''):
        self.__method = method
    
    @asynchronous
    def get(self):
        if self.__method == 'get_dynamic_num':
            max_id = int(self.get_argument('id', 0))
            self.__get_dynamic_num(max_id)
            
            
    def __get_dynamic_num(self, id):
        if self.request.connection.stream.closed():
            return
        sql = "SELECT count(*) AS nr, max(`id`) AS md FROM `question` WHERE `id` > %d" % id
        conn = config.getDBConnect()
        try:
            row = conn.get(sql)
            if row <> None and len(row) > 0 and row.nr > 0:
                res = []
                res.append(row.nr)
                res.append(row.md)
                self.write(json.dumps(res))
                self.finish()
            else:
                tornado.ioloop.IOLoop.instance().add_timeout(
                    time.time() + 0.5,
                    lambda: self.__get_dynamic_num(id)
                ) 
        except:
            self.write('')
            self.finish()
            